# -*- coding: utf-8 -*-

"""
京东配送API SDK 数据模型
"""

from typing import Dict, Any, Optional, List
import json


class ApiConfig:
    """API配置类"""
    
    def __init__(self, app_key: str, app_secret: str, merchant_no: str,
                 sandbox_mode: bool = False, timeout: int = 30, 
                 enable_log: bool = True, user_agent: Optional[str] = None):
        """
        初始化API配置
        
        Args:
            app_key: 应用密钥
            app_secret: 应用密码
            merchant_no: 商户号
            sandbox_mode: 是否沙箱模式
            timeout: 请求超时时间（秒）
            enable_log: 是否启用日志
            user_agent: 用户代理
        """
        self.app_key = app_key
        self.app_secret = app_secret
        self.merchant_no = merchant_no
        self.sandbox_mode = sandbox_mode
        self.timeout = timeout
        self.enable_log = enable_log
        self.user_agent = user_agent or "JingdongApiSDK-Python/1.0.0"
        
        self.validate()
    
    def validate(self):
        """验证配置"""
        if not self.app_key:
            raise ValueError("app_key 不能为空")
        
        if not self.app_secret:
            raise ValueError("app_secret 不能为空")
        
        if not self.merchant_no:
            raise ValueError("merchant_no 不能为空")
        
        if self.timeout <= 0:
            raise ValueError("timeout 必须大于0")


class ApiResult:
    """API结果类"""
    
    def __init__(self, success: bool = False, code: int = 0, 
                 message: str = "", data: Optional[Dict[str, Any]] = None,
                 request_id: str = ""):
        """
        初始化API结果
        
        Args:
            success: 是否成功
            code: 响应码
            message: 响应消息
            data: 响应数据
            request_id: 请求ID
        """
        self.success = success
        self.code = code
        self.message = message
        self.data = data
        self.request_id = request_id
    
    @classmethod
    def success_result(cls, data: Optional[Dict[str, Any]] = None, 
                      message: str = "请求成功", request_id: str = ""):
        """创建成功结果"""
        return cls(True, 0, message, data, request_id)
    
    @classmethod
    def error_result(cls, code: int, message: str, 
                    data: Optional[Dict[str, Any]] = None, request_id: str = ""):
        """创建失败结果"""
        return cls(False, code, message, data, request_id)
    
    @classmethod
    def from_response(cls, response: Dict[str, Any]):
        """从API响应创建结果"""
        code = response.get("code", -1)
        message = response.get("message", "未知错误")
        data = response.get("data")
        request_id = response.get("request_id", "")
        success = code == 0
        
        return cls(success, code, message, data, request_id)
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典"""
        return {
            "success": self.success,
            "code": self.code,
            "message": self.message,
            "data": self.data,
            "request_id": self.request_id
        }
    
    def to_json(self) -> str:
        """转换为JSON字符串"""
        return json.dumps(self.to_dict(), ensure_ascii=False)
    
    def __str__(self) -> str:
        return self.to_json()


class OrderData:
    """订单数据类"""
    
    def __init__(self, order_id: str, recipient_name: str, recipient_phone: str,
                 recipient_address: str, recipient_lng: float, recipient_lat: float,
                 total_weight: float, sender_lng: float, sender_lat: float,
                 sender_name: str, sender_phone: str, sender_address: str,
                 **kwargs):
        """
        初始化订单数据
        
        Args:
            order_id: 订单号
            recipient_name: 收件人姓名
            recipient_phone: 收件人电话
            recipient_address: 收件人地址
            recipient_lng: 收件人经度
            recipient_lat: 收件人纬度
            total_weight: 物品重量（kg）
            sender_lng: 发件人经度
            sender_lat: 发件人纬度
            sender_name: 发件人姓名
            sender_phone: 发件人电话
            sender_address: 发件人地址
            **kwargs: 其他可选参数
        """
        # 必填字段
        self.order_id = order_id
        self.recipient_name = recipient_name
        self.recipient_phone = recipient_phone
        self.recipient_address = recipient_address
        self.recipient_lng = recipient_lng
        self.recipient_lat = recipient_lat
        self.total_weight = total_weight
        self.sender_lng = sender_lng
        self.sender_lat = sender_lat
        self.sender_name = sender_name
        self.sender_phone = sender_phone
        self.sender_address = sender_address
        
        # 可选字段
        self.trade_order_source = kwargs.get('trade_order_source', 1)
        self.trade_order_id = kwargs.get('trade_order_id')
        self.service_code = kwargs.get('service_code', 'STANDARD')
        self.prebook = kwargs.get('prebook', 0)
        self.operator_name = kwargs.get('operator_name')
        self.carrier_merchant_id = kwargs.get('carrier_merchant_id')
        self.ext_info = kwargs.get('ext_info', {})
        self.order_sequence = kwargs.get('order_sequence')
        self.pre_delivery_fee = kwargs.get('pre_delivery_fee')
        self.expected_delivery_time = kwargs.get('expected_delivery_time')
        self.expected_pickup_time = kwargs.get('expected_pickup_time')
        self.expected_left_delivery_time = kwargs.get('expected_left_delivery_time')
        self.expected_right_delivery_time = kwargs.get('expected_right_delivery_time')
        self.insured_mark = kwargs.get('insured_mark')
        self.total_value = kwargs.get('total_value')
        self.total_volume = kwargs.get('total_volume')
        self.rider_pick_method = kwargs.get('rider_pick_method')
        self.tip_fee = kwargs.get('tip_fee')
        self.goods_details = kwargs.get('goods_details')
        self.order_remark = kwargs.get('order_remark')
        self.shop_remark = kwargs.get('shop_remark')
        self.carrier_shop_id = kwargs.get('carrier_shop_id')
        self.operator_phone = kwargs.get('operator_phone')
        self.car_model_code = kwargs.get('car_model_code')
        self.rider_info = kwargs.get('rider_info')
        self.category = kwargs.get('category')
        
        self.validate()
    
    def validate(self):
        """验证必填字段"""
        required_fields = {
            'order_id': '订单号',
            'recipient_name': '收件人姓名',
            'recipient_phone': '收件人电话',
            'recipient_address': '收件人地址',
            'recipient_lng': '收件人经度',
            'recipient_lat': '收件人纬度',
            'total_weight': '物品重量',
            'sender_lng': '发件人经度',
            'sender_lat': '发件人纬度',
            'sender_name': '发件人姓名',
            'sender_phone': '发件人电话',
            'sender_address': '发件人地址'
        }
        
        for field, desc in required_fields.items():
            value = getattr(self, field)
            if value is None or (isinstance(value, str) and not value.strip()):
                raise ValueError(f"{desc} 不能为空")
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典"""
        result = {}
        for key, value in self.__dict__.items():
            if value is not None:
                result[key] = value
        return result


class MerchantInfo:
    """商户信息类"""
    
    def __init__(self, merchant_name: str, merchant_phone: str, merchant_address: str,
                 business_license: str, contact_person: str, contact_phone: str,
                 merchant_type: str = "1"):
        """
        初始化商户信息
        
        Args:
            merchant_name: 商户名称
            merchant_phone: 商户电话
            merchant_address: 商户地址
            business_license: 营业执照
            contact_person: 联系人
            contact_phone: 联系电话
            merchant_type: 商户类型
        """
        self.merchant_name = merchant_name
        self.merchant_phone = merchant_phone
        self.merchant_address = merchant_address
        self.business_license = business_license
        self.contact_person = contact_person
        self.contact_phone = contact_phone
        self.merchant_type = merchant_type
        
        self.validate()
    
    def validate(self):
        """验证必填字段"""
        required_fields = {
            'merchant_name': '商户名称',
            'merchant_phone': '商户电话',
            'merchant_address': '商户地址',
            'business_license': '营业执照',
            'contact_person': '联系人',
            'contact_phone': '联系电话'
        }
        
        for field, desc in required_fields.items():
            value = getattr(self, field)
            if not value or not value.strip():
                raise ValueError(f"{desc} 不能为空")
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典"""
        return {
            'merchant_name': self.merchant_name,
            'merchant_phone': self.merchant_phone,
            'merchant_address': self.merchant_address,
            'business_license': self.business_license,
            'contact_person': self.contact_person,
            'contact_phone': self.contact_phone,
            'merchant_type': self.merchant_type
        }
